package com.zwcl.glass.goods.service.impl;

import com.zwcl.common.core.exception.BusinessException;
import com.zwcl.glass.goods.entity.GoodsSpu;
import com.zwcl.glass.goods.enums.GlassCateEnum;
import com.zwcl.glass.goods.enums.GlassTagsScoreEnum;
import com.zwcl.glass.goods.service.GoodsCommonService;
import com.zwcl.glass.goods.service.GoodsRecommend;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service(value="GlassSpuRecommend")
@Slf4j
public class GlassSpuRecommend extends GoodsRecommend {

    @Autowired
    private GoodsCommonService goodsCommonService;

    @Override
    public List<GoodsSpu> getSpusByUserTag(String userTags,List<String> selectTags) {
        try {
            //获取镜片的标签
            //String glassTags=userTags.get(paperCode);
            if (StringUtils.isNotBlank(userTags)) {                      //有用户标签
                log.info("用户的镜片标签：{}", userTags);
                String[] userTagClassArr = userTags.split(";");
                //拆开用户的所有的标签
                Map<String, String> userTagMap = new HashMap<>();
                for (String userTagClass : userTagClassArr) {
                    String[] userTagArr = userTagClass.trim().split(":");
                    if (userTagMap.containsKey(userTagArr[0])) {
                        String appendTags = userTagMap.get(userTagArr[0]) + "," + userTagArr[1];
                        userTagMap.put(userTagArr[0], appendTags);
                    } else {
                        userTagMap.put(userTagArr[0], userTagArr[1]);
                    }
                }
                //查询所有的镜片，目前分类是写死
                List<GoodsSpu> goodsSpuList = goodsCommonService.getSpuByCateCode(GlassCateEnum.GLASS.getValue());
                //先根据折射率获取镜片
                String refractionTag = userTagMap.get(GlassTagsScoreEnum.REFRACTION.getValue());
                goodsSpuList = filterSpusByRefraction(goodsSpuList, refractionTag);
                //移除折射率标签
                userTagMap.remove(GlassTagsScoreEnum.REFRACTION.getValue());

                //对用户选择的细分标签进行匹配
                //TODO:这个可能没用了
                goodsSpuList=matchTags(goodsSpuList,selectTags,GlassCateEnum.GLASS.getValue());

                //对镜片根据其他的标签进行打分排序
                if (userTagMap.size() > 0 && null!=goodsSpuList) {
                    Iterator<GoodsSpu> it = goodsSpuList.iterator();
                    while(it.hasNext()){
                        GoodsSpu item = it.next();
                        Integer score = computeSpuScore(item.getTags(), userTagMap);
                        item.setScore(score);
                        if(score<5){
                            it.remove();
                        }
                    }
//                    goodsSpuList.forEach(item -> {
//                        Integer score = computeSpuScore(item.getTags(), userTagMap);
//                        item.setScore(score);
//                    });
//                    //过滤匹配大于5分的数据
//                    goodsSpuList=goodsSpuList.stream().filter(x->x.getScore()>5).collect(Collectors.toList());
                    //对商品进行排序
                    Collections.sort(goodsSpuList, new Comparator<GoodsSpu>() {
                        @Override
                        public int compare(GoodsSpu A1, GoodsSpu A2) {
                            return A2.getScore().compareTo(A1.getScore());
                        }
                    });
                }
                return goodsSpuList;
            }
            return null;
        }catch (Exception ex){
            log.error("镜片推荐失败：{}",ex);
            throw new BusinessException("镜片推荐失败");
        }
    }


    /**
     * 先根据折射率过滤镜片
     * TODO: 折射率的中的镜片，可能是有序的
     * @param goodsSpuList
     * @param refractionTag
     * @return
     */
    private List<GoodsSpu> filterSpusByRefraction(List<GoodsSpu> goodsSpuList,String refractionTag ){
        if(StringUtils.isNotBlank(refractionTag)) {
            //可能适合多个折射率
            String[] refractionArr = refractionTag.split(",");
            //根据折射率查询spu 或者sku
            goodsSpuList = goodsSpuList.stream().filter(x->{
                Boolean matchflag =false;
                for(String refraction : refractionArr){
                    //TODO:分割符号变化
                    if(x.getTags().contains("|"+refraction+"|")) {
                        matchflag = true;
                        break;
                    }
                }
                return matchflag;
            }).collect(Collectors.toList());
        }
        return goodsSpuList;
    }

    @Override
    public Integer computeSpuScore(String spuTags, Map<String, String> userTags) {
        Integer totalScore = 0;
        String[] spuTagsArr= spuTags.split("\\|");
        Set<String> spuTagsSet=new HashSet<>();
        for(int j=0;j<spuTagsArr.length;j++){
            if(StringUtils.isNotBlank(spuTagsArr[j])){
                spuTagsSet.add(spuTagsArr[j].trim());
            }
        }
        for(Map.Entry<String,String> item : userTags.entrySet()){
            //一个分类下，有多个标签
            log.info("用户标签：{}",item.getValue());
            String[] tagItemArr = item.getValue().split(",");
            for(int i=0;i<tagItemArr.length;i++){
//                //TODO:分割符号变化
//                if(spuTags.contains("|"+tagItemArr[i].trim()+"|")){
//                    totalScore += GlassTagsScoreEnum.of(item.getKey()).getWeight();
//                }
                if(spuTagsSet.contains(tagItemArr[i].trim())){
                    totalScore += GlassTagsScoreEnum.of(item.getKey()).getWeight();
                }
            }
        }
        return totalScore;
    }
}
